<template>
  <el-dialog title="添加日程" :visible.sync="dialogFormVisible">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item required label="日程标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>

      <el-form-item label="日期" required>
        <el-col :span="11">
          <el-form-item prop="kssj">
            <el-date-picker
              v-model="form.kssj"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="开始时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item
            prop="jssj"
          ><el-date-picker
            v-model="form.jssj"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="结束时间"
            style="width: 100%"
          /></el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="是否公开" prop="sfgk" required>
        <el-switch v-model="form.sfgk" />
      </el-form-item>
      <el-form-item label="日程级别" prop="rcjb" required>
        <el-radio-group v-model="form.rcjb">
          <el-radio label="1">一般日程</el-radio>
          <el-radio label="2">重要日程</el-radio>
          <el-radio label="3">紧急日程</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 授权部分 准备用添加部门的方式 -->
      <el-form-item
        label="安排部门"
        prop="sysOrganizations"
        :class="organizationVisiable === false ? 'active' : ''"
      >
        <el-button
          type="primary"
          @click="
            dialogTransferVisible = true; //绑定多个方法时，要用分号做分隔号，且非表示式的方法一定要加小括号，不加不生效
            getDepts();
          "
        >
          部门授权
        </el-button>
        <el-dialog
          title="部门授权"
          :visible.sync="dialogTransferVisible"
          append-to-body
        >
          <treeTransfer
            ref="treeTransfer"
            :datas="data"
            :default-props="defaultProps"
          />
        </el-dialog>
        <span>{{ "(" + data[0].id + ")" }}</span>
      </el-form-item>

      <!-- <el-form-item label="安排人员" prop="sysUserMembers">
                  <el-button
                    type="primary"
                    @click="dialogTransferVisible = true"
                  >
                    用户授权
                  </el-button>
                  <el-dialog
                    title="用户授权"
                    :visible.sync="dialogTransferVisible"
                    :append-to-body="true"
                  >
                    <el-transfer v-model="value" :data="data"></el-transfer>
                  </el-dialog>
                </el-form-item> -->
      <el-form-item label="日程描述" prop="content" required>
        <el-input v-model="form.content" type="textarea" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button @click="resetForm('form')">重置</el-button>
      <el-button type="primary" @click="addSchedule('form')">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { saveSchedule } from '@/api/schedule/schedule'
import { getDepts, getDeptSuperior } from '@/api/system/dept'
import treeTransfer from '@/views/components/TreeTransfer.vue'

export default {
  name: 'LeftTop',
  components: { treeTransfer },
  data() {
    var validateDate = (rule, endTime, callback) => {
      // 验证日期（判断结束日期是否大于开始日期）日期格式为YY—MM—DD
      var startTime = this.form.kssj
      if (!endTime) {
        return callback(new Error('结束时间不能为空'))
      }
      setTimeout(() => {
        if (startTime.length > 0 && endTime.length > 0) {
          var startTmp = startTime.split('-')
          var endTmp = endTime.split('-')
          var sd = new Date(startTmp[0], startTmp[1], startTmp[2])
          var ed = new Date(endTmp[0], endTmp[1], endTmp[2])
          if (sd.getTime() > ed.getTime()) {
            callback(new Error('开始日期不能大于结束日期'))
          } else {
            callback()
          }
        }
      }, 1000)
    }
    return {
      deptDatas: [],
      depts: [],
      dialogFormVisible: false,
      dialogTransferVisible: false,
      organizationVisiable: false,

      form: {
        fqr: '',
        title: '',
        kssj: '',
        jssj: '',
        sfgk: true,
        rcjb: '',
        sysOrganizations: '',
        sysUserMembers: '',
        content: '',
        desc: ''
      },

      rules: {
        title: [{ required: true, message: '请输入日程标题', trigger: 'blur' }],
        kssj: [
          {
            required: true,
            message: '请选择开始时间',
            trigger: 'change'
          }
        ],
        jssj: [
          {
            required: true,
            validator: validateDate,
            message: '请选择结束时间且开始日期不能大于结束日期',
            trigger: 'change'
          }
        ],
        rcjb: [
          {
            required: true,
            message: '请选择日程级别',
            trigger: 'change'
          }
        ],
        content: [
          { required: true, message: '请描述日程内容', trigger: 'blur' }
        ]
      },

      data: [
        {
          id: '1',
          pid: 0,
          label: '顶点大学  ',
          children: [
            {
              id: '1-1',
              pid: '1',
              label: '二级 1-1',
              children: []
            },
            {
              id: '1-2',
              pid: '1',
              label: '二级 1-2',
              children: [
                {
                  id: '1-2-1',
                  pid: '1-2',
                  children: [],
                  label: '二级 1-2-1'
                },
                {
                  id: '1-2-2',
                  pid: '1-2',
                  children: [
                    {
                      id: '1-3-1',
                      pid: '1-2-2',
                      children: [],
                      label: '三级 1-3-1'
                    },
                    {
                      id: '1-3-2',
                      pid: '1-2-2',
                      children: [],
                      label: '三级 1-3-2'
                    }
                  ],
                  label: '二级 1-2-2'
                }
              ]
            }
          ]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      }

      // data: generateData()
    }
  },
  methods: {
    openDialog(params) {
      this.dialogFormVisible = true
      if (params) {
        this.organizationVisiable = true
        // console.log(this.organizationVisiable + "-----");
      } else {
        this.organizationVisiable = false
        // console.log(this.organizationVisiable + "++++");
      }
    },
    // close() {
    //   this.$emit("close");
    // },
    getDeptDatas(node, resolve) {
      const sort = 'id,desc'
      const params = { sort: sort }
      if (typeof node !== 'object') {
        if (node) {
          params['blurry'] = node
        }
      } else if (node.level !== 0) {
        params['pid'] = node.data.id
      }
      setTimeout(() => {
        getDepts(params).then(res => {
          if (resolve) {
            resolve(res.content)
          } else {
            this.deptDatas = res.content
          }
        })
      }, 100)
      // console.log(this.deptDatas);
    },

    // 获取部门数据
    getDepts() {
      (async() => {
        try {
          const getdepts = await getDepts({ enabled: true })

          this.depts = getdepts.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          console.log(this.depts)
        } catch (error) {
          console.log(error)
        }
      })()
    },

    addSchedule(formName) {
      const userid = this.$store.getters.user.username
      this.form.fqr = userid
      this.$refs[formName].validate(valid => {
        if (valid) {
          // this.getDeptDatas(1);
          (async() => {
            try {
              await saveSchedule(this.form)
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.$emit('initData')
              this.dialogFormVisible = false
            } catch (error) {
              this.$message({
                message: '保存失败！',
                type: 'warning'
              })
            }
          })()
        }
      })
    },

    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    getCurrentWeekMondayDate() {
      var now1 = new Date()
      var nowTime1 = now1.getTime()
      var day1 = now1.getDay() || 7 // 不加 || 7.周末会变成下周一
      var oneDayTime1 = 24 * 60 * 60 * 1000
      var MondayTime1 = nowTime1 - (day1 - 1) * oneDayTime1 // 显示周一
      // console.log(MondayTime1);
      var currentWeekMondayTime = new Date(MondayTime1)
      var year = currentWeekMondayTime.getFullYear()
      var month = currentWeekMondayTime.getMonth() + 1
      var day = currentWeekMondayTime.getDate()
      return year + '-' + month + '-' + day
    },
    validateDate(startTime, endTime, callback) {
      // 验证日期（判断结束日期是否大于开始日期）日期格式为YY—MM—DD
      if (!endTime) {
        return callback(new Error('结束时间不能为空'))
      }
      setTimeout(() => {
        if (startTime.length > 0 && endTime.length > 0) {
          var startTmp = startTime.split('-')
          var endTmp = endTime.split('-')
          var sd = new Date(startTmp[0], startTmp[1], startTmp[2])
          var ed = new Date(endTmp[0], endTmp[1], endTmp[2])
          if (sd.getTime() > ed.getTime()) {
            callback(new Error('开始日期不能大于结束日期'))
          } else {
            callback()
          }
        }
      }, 1000)
    },

    queryOri() {}
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}
.active {
  display: none;
}
</style>
